package com.example.ymm.modules1.controller.hl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.ymm.model.CommonResult;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.controller.BaseController;
import com.example.ymm.modules1.entity.hl.dkn.DknTrialItem;
import com.example.ymm.modules1.entity.hl.dkn.DknTrialLog;
import com.example.ymm.modules1.entity.hl.yw.*;
import com.example.ymm.modules1.entity.ms.DDepartment;
import com.example.ymm.modules1.entity.ms.DEmployee;
import com.example.ymm.modules1.entity.ms.VSellClient;
import com.example.ymm.modules1.entity.ms.VYXXiaoShouYuShouKuanH;
import com.example.ymm.modules1.entity.my.user.DbUser;
import com.example.ymm.modules1.query.hl.*;
import com.example.ymm.modules1.query.ms.DEmployeeQueryCriteria;
import com.example.ymm.modules1.query.ms.VSellClientQueryCriteria;
import com.example.ymm.modules1.service.dto.heng.*;
import com.example.ymm.modules1.service.dto.ms.CountMoneyAffirmDto;
import com.example.ymm.modules1.service.dto.ms.MsMoneyAffirmDto;
import com.example.ymm.modules1.service.dto.ms.MsMoneyAffirmOrderDto;
import com.example.ymm.modules1.service.hl.*;
import com.example.ymm.modules1.service.ms.DDepartmentService;
import com.example.ymm.modules1.service.ms.DEmployeeService;
import com.example.ymm.modules1.service.ms.VSellClientService;
import com.example.ymm.modules1.service.ms.VYXXiaoShouYuShouKuanHService;
import com.example.ymm.modules1.service.user.DbUserService;
import com.example.ymm.modules1.service.xft.XftService;
import com.example.ymm.util.*;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/hl/heng/manage/dept")
@Tag(name = "hl 业务部门管理")
@Slf4j
public class YwDeptController extends BaseController {

    @Autowired
    YwDeptService ywDeptService;

    @Autowired
    YwGroupService ywGroupService;

    @Autowired
    DDepartmentService dDepartmentService;

    @Autowired
    YwMoneyAffirmLogService ywMoneyAffirmLogService;

    @Autowired
    YwCommissionConfigService ywCommissionConfigService;

    @Autowired
    DEmployeeService dEmployeeService;

    @Autowired
    YwAccountOutoRateService ywAccountOutoRateService;

    @Autowired
    YwApproveService ywApproveService;

    @Autowired
    YwDeptMainRateService ywDeptMainRateService;

    @Autowired
    YwDeptNextRateService ywDeptNextRateService;

    @Autowired
    VSellClientService vSellClientService;

    @Autowired
    XftService xftService;

    @Autowired
    VYXXiaoShouYuShouKuanHService vyxXiaoShouYuShouKuanHService;

    @Autowired
    YwMoneyOrderNoStorageService ywMoneyOrderNoStorageService;

    @Autowired
    YwIntroduceUserService ywIntroduceUserService;

    @Autowired
    DbUserService dbUserService;

    @Value("${spring.profiles.active}")
    String PD_MATCH;
    @Autowired
    DknTrialItemService dknTrialItemService;


    @Autowired
    DknTrialLogService dknTrialLogService;

    @Autowired
    YwUserService ywUserService;

    @Autowired
    YwExcludeFapiaoItemService ywExcludeFapiaoItemService;


    @Schema( name =  "营销组列表")
    @PostMapping("/ywDeptList")
    public CommonResult ywDeptList(@Valid YwDeptQueryCriteria criteria, YmPageDto ymPage) {
        try {
            TableList<YwDept> list = ywDeptService.list(criteria, ymPage);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "营销组下拉列表")
    @PostMapping("/ywDeptSelectList")
    public CommonResult ywDeptSelectList(@Valid YwDeptQueryCriteria criteria) {
        try {
            List<YwDept> list = ywDeptService.queryAll(criteria);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @Schema( name =  "营销组保存")
    @PostMapping("/ywDeptSave")
    public CommonResult ywDeptSave(YwDept dept) {
        try {
            if (UtilValidate.isNotEmpty(dept.getDeptNo())) {
                DDepartment dDepartment = dDepartmentService.getByDeptNo(dept.getDeptNo());
                if (UtilValidate.isNotEmpty(dDepartment)) {
                    dept.setDeptName(dDepartment.getName());
                }
            }
//            if (UtilValidate.isNotEmpty(dept.getGroupId())) {
//                YwGroup group = ywGroupService.getById(dept.getGroupId());
//                if (UtilValidate.isNotEmpty(group)) {
//                    dept.setGroupName(group.getGroupName());
//                }
//            }
            ywDeptService.saveOrUpdate(dept);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "营销组详情")
    @PostMapping("/ywDeptDetail")
    public CommonResult dictDetail(@Parameter(name = "数据主键") @RequestParam(required = true) String deptId) {
        try {
            YwDept dict = ywDeptService.getById(deptId);

            return CommonResult.success(dict);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "营销组删除")
    @RequestMapping(value = "/ywDeptDelete", method = RequestMethod.POST)
    public CommonResult ywDeptDelete(@Parameter(name = "数据主键") @RequestParam(required = true) String deptId) {
        try {
            ywDeptService.removeById(deptId);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "部门列表")
    @RequestMapping(value = "/ywGroupList", method = RequestMethod.POST)
    public CommonResult ywGroupList(@Valid YwGroupQueryCriteria criteria, YmPageDto ymPage) {
        try {
            TableList<YwGroup> list = ywGroupService.list(criteria, ymPage);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "部门下拉")
    @RequestMapping(value = "/ywGroupSelectList", method = RequestMethod.POST)
    public CommonResult ywGroupSelectList(@Valid YwGroupQueryCriteria criteria) {
        try {
            List<YwGroup> list = ywGroupService.queryAll(criteria);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "部门保存")
    @RequestMapping(value = "/ywGroupSave", method = RequestMethod.POST)
    public CommonResult ywGroupSave(YwGroup group) {
        try {

            ywGroupService.saveOrUpdate(group);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "部门详情")
    @RequestMapping(value = "/ywGroupDetail", method = RequestMethod.POST)
    public CommonResult groupDetail(@Parameter(name = "数据主键") @RequestParam(required = true) String groupId) {
        try {
            YwGroup group = ywGroupService.getById(groupId);

            return CommonResult.success(group);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "部门删除")
    @RequestMapping(value = "/ywGroupDelete", method = RequestMethod.POST)
    public CommonResult ywGroupDelete(@Parameter(name = "数据主键") @RequestParam(required = true) String groupId) {
        try {
            ywGroupService.removeById(groupId);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "业务待抽成列表")
    @RequestMapping(value = "/msMoneyAffirmList", method = RequestMethod.POST)
    public CommonResult msMoneyAffirmList(@Valid YwMoneyAffirmLogQueryCriteria criteria, YmPageDto ymPage) {
        try {
            String userName = getUserName();
            String userRole = getUserRole();
            if (!"manage".equals(userRole)) {
                criteria.setUserNameLogin(userName);
                /**
                 * 查询是否经理 经理可查看整个部门 切勿放开会有bug
                 * 先本地测试
                 */

                DEmployee userInfo = dEmployeeService.getUserInfo(userName);
                if(UtilValidate.isNotEmpty(userInfo)){
                    String dname = userInfo.getDname();
                    if("钟营销部".equals(dname)){
                        criteria.setOrderType("asc");
                    }
                }
                //
//                YwDeptQueryCriteria c2=new YwDeptQueryCriteria();
//                c2.setManageUserName(userName);
//                List<YwDept> ywDepts = ywDeptService.queryAll(c2);
//                if(UtilValidate.isNotEmpty(ywDepts)) {
//                    criteria.setUserNameLogin(null);
//                    criteria.setSalesmanDeptName0Like(ywDepts.get(0).getDeptName());
//                }
            }
            TableList<MsMoneyAffirmDto> list = ywMoneyAffirmLogService.list(criteria, ymPage);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {

            log.error(e.getMessage(), e);
            String userName = getUserName();
            EmailUtil.sendEmail("1055162826@qq.com","业务员:"+userName+"获取抽成列表报错:"+DateKit.getStringNowTime(),e.getMessage());
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "业务待抽成列表 尾行进行合计")
    @PostMapping("/countMoneyAffirm")
    public CommonResult countMoneyAffirm(@Valid YwMoneyAffirmLogQueryCriteria criteria) {
        try {
            String userName = getUserName();
            String userRole = getUserRole();
            if ("ms_user".equals(userRole)) {
                criteria.setUserNameLogin(userName);
            }
            CountMoneyAffirmDto dto = ywMoneyAffirmLogService.countMoneyAffirm(criteria);
            return CommonResult.success(dto, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "导出业务明细")
    @PostMapping("/exportMoneyChild")
    public CommonResult exportMoneyAffirm(@RequestBody List<MsMoneyAffirmDto> list) {
        try {
            if(UtilValidate.isEmpty(list)){
                return CommonResult.error("非法参数!");
            }
            List<String> skuNoIn=new ArrayList<>();
            List<String> yushouNoIn=new ArrayList<>();
            for (MsMoneyAffirmDto dto : list) {
                if(UtilValidate.isNotEmpty(dto.getType())){
                    if("收款确认".equals(dto.getType())){
                        skuNoIn.add(dto.getOrderNo());
                    }else{
                        yushouNoIn.add(dto.getOrderNo());
                    }
                }
            }
            List<YuShouItem>  dataList=new ArrayList<>();
            if(UtilValidate.isNotEmpty(skuNoIn)){
                FaPiaoItemQueryCriteria criteria1=new FaPiaoItemQueryCriteria();
                criteria1.setSkqrNoIn(skuNoIn);
                List<FaPiaoItem> faPiaoItems = ywMoneyAffirmLogService.shouKuanQueRenItemList(criteria1);
                if(UtilValidate.isNotEmpty(faPiaoItems)){
                    dataList.addAll(faPiaoItems);
                }
            }
            if(UtilValidate.isNotEmpty(yushouNoIn)){
                FaPiaoItemQueryCriteria criteria2=new FaPiaoItemQueryCriteria();
                criteria2.setSkqrNoIn(yushouNoIn);
                List<YuShouItem> faPiaoItems = ywMoneyAffirmLogService.yushoukuanItemList(criteria2);
                if(UtilValidate.isNotEmpty(faPiaoItems)){
                    dataList.addAll(faPiaoItems);
                }
            }

            return CommonResult.success(dataList, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "抽成点数配置列表")
    @PostMapping("/commissionConfigList")
    public CommonResult commissionConfigList(@Valid YwCommissionConfigQueryCriteria criteria, YmPageDto ymPage) {
        try {
            TableList<YwCommissionConfig> list = ywCommissionConfigService.list(criteria, ymPage);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "抽成点数保存")
    @PostMapping("/commissionConfigSave")
    public CommonResult commissionConfigSave(YwCommissionConfig config) {
        try {

            ywCommissionConfigService.saveOrUpdate(config);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "抽成点数删除")
    @PostMapping("/commissionConfigDelete")
    public CommonResult commissionConfigDelete(
            @Parameter(name = "数据主键") @RequestParam(required = true) String commissionId) {
        try {
            ywCommissionConfigService.removeById(commissionId);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "业务员下拉列表")
    @RequestMapping(value = "/ywUserSelectList", method = RequestMethod.POST)
    public CommonResult ywUserSelectList() {
        try {
            DEmployeeQueryCriteria criteria = new DEmployeeQueryCriteria();
            List<YwDept> depts = ywDeptService.queryAll(null);
            List<String> deptNos = depts.stream().map(YwDept::getDeptNo).collect(Collectors.toList());
            criteria.setDtidIn(deptNos);
            List<DEmployee> list = dEmployeeService.queryAll(criteria);

            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "业务员固定比例列表")
    @PostMapping("/accountOutoRateList")
    public CommonResult accountOutoRateList(@Valid YwAccountOutoRateQueryCriteria criteria, YmPageDto ymPage) {
        try {
            TableList<YwAccountOutoRate> list = ywAccountOutoRateService.list(criteria, ymPage);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "业务员固定比例保存")
    @PostMapping("/accountOutoRateSave")
    public CommonResult accountOutoRateSave(YwAccountOutoRate outoRate) {
        try {
            if (UtilValidate.isEmpty(outoRate.getReceiverUserName())) {
                return CommonResult.error("接单人不能为空");
            }
//            YwAccountOutoRateQueryCriteria criteria = new YwAccountOutoRateQueryCriteria();
//            criteria.setReceiverUserName(outoRate.getReceiverUserName());
//            if(UtilValidate.isEmpty(outoRate.getId())){
//                List<YwAccountOutoRate> queryAll = ywAccountOutoRateService.queryAll(criteria);
//                if (UtilValidate.isNotEmpty(queryAll)) {
//                    return CommonResult.error("接单人已存在");
//                }
//            }

            ywAccountOutoRateService.saveOrUpdate(outoRate);
            ywMoneyAffirmLogService.initFn();
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "业务员固定比例删除")
    @PostMapping("/accountOutoRateDelete")
    public CommonResult accountOutoRateDelete(
            @Parameter(name = "数据主键") @RequestParam(required = true) String id) {
        try {
            ywAccountOutoRateService.removeById(id);
            ywMoneyAffirmLogService.initFn();

            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "业务员抽成审批列表")
    @PostMapping("/ywApproveList")
    public CommonResult ywApproveList(@Valid YwApproveQueryCriteria criteria, YmPageDto ymPage) {
        try {
            String userName = getUserName();
            String userRole = getUserRole();

            boolean is_show_all=false;//是否拥有查看所有数据的权限
            if ("manage".equals(userRole)) {
                is_show_all=true;
            }
            if(!is_show_all){
                DEmployee employee = ywUserService.getUserInfoToSlave2(userName);
                if(UtilValidate.isNotEmpty(employee)){
                    if(employee.getDname().equals("结算部")){//财务结算部
                        is_show_all=true;
                    }
                }
            }
            if(userName.equals("邵琪")||userName.equals("庄嫚艺")){
                is_show_all=true;
            }
            if (!is_show_all) {
                criteria.setUserName(userName);
            }
            TableList<YwApprove> list = ywApproveService.list(criteria, ymPage);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "业务员抽成审批列表(薪福通)")
    @PostMapping("/xftList")
    public CommonResult xftList(@Valid YwApproveQueryCriteria criteria, YmPageDto ymPage) {
        try {

            TableList<YwApprove> list = ywApproveService.xftList(criteria, ymPage);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "业务员抽成记录列表")
    @PostMapping("/moneyAffrimLogList")
    public CommonResult moneyAffrimLogList(String approveNo) {
        try {
            if (UtilValidate.isEmpty(approveNo)) {
                return CommonResult.error("审批单号不能为空");
            }
            List<YwMoneyAffirmLog> list = ywMoneyAffirmLogService.listByApproveNo(approveNo);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "重新获取固定比例数据")
    @PostMapping("/refetch")
    public CommonResult refetch() {
        try {
            ywMoneyAffirmLogService.refetch();
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "提起审批前-进行流程试算")
    @PostMapping("/approveCreateBefore")
    public CommonResult approveCreateBefore(@RequestBody YwApproveCreateDto dto) {
        try {
            String userName = getUserName();
            String userRole = getUserRole();
            if ("manage".equals(userRole)) {
                userName ="刘庆峰";
            }
            DbUser dbUser = dbUserService.findByUserName(userName);
            if(UtilValidate.isNotEmpty(dbUser)){
                dto.setUserId(dbUser.getUserId());
            }
            //           String userNo = dEmployeeService.getTidByName(userName);
//            dto.setUserNo(userNo);
            dto.setUserName(userName);

            List<MsMoneyAffirmDto> list = dto.getList();
            ApproveRespond respond = new ApproveRespond();
            List<String> msg = new ArrayList<>();
            if (UtilValidate.isEmpty(list)) {
                msg.add("请选择要提交的数据！");
            }
            List<String> orderIn = new ArrayList<>();

            for (int i = 0; i < list.size(); i++) {
                MsMoneyAffirmDto dto1 = list.get(i);
                orderIn.add(dto1.getOrderNo());
            }
            DknTrialItemQueryCriteria c2=new DknTrialItemQueryCriteria();
            c2.setOrderNoIn(orderIn);
            List<DknTrialItem> dknTrialItems = dknTrialItemService.queryAll(c2);
            if(UtilValidate.isNotEmpty(dknTrialItems)) {
                msg.add("当前付款编号已提交过不可重复提交！");
            }
            if(UtilValidate.isNotEmpty(msg)) {
                respond.setErrorMsg(msg);
                return CommonResult.success(respond);
            }
            CreateOrderNo createOrderNo = new CreateOrderNo();
            String orderNum = createOrderNo.makeOrderNum("YW");

            String stringNowTime = DateKit.getStringNowTime();
            respond.setSubTime(stringNowTime);
            dto.setSubTime(stringNowTime);
            DknTrialLog dknTrialLog=new DknTrialLog();
            dknTrialLog.setUserId(dto.getUserId());
            dknTrialLog.setUserName(dto.getUserName());
            dknTrialLog.setList(JSONArray.toJSONString(dto.getList()));
            dknTrialLog.setType(dto.getType());
            dknTrialLog.setIsRead(0);
            dknTrialLog.setApproveNo(orderNum);
            dknTrialLogService.save(dknTrialLog);


            List<DknTrialItem> trialItems = new ArrayList<>();
            for (MsMoneyAffirmDto item : list) {
                DknTrialItem dknTrialItem = new DknTrialItem();
                dknTrialItem.setPId(dknTrialLog.getId());
                dknTrialItem.setOrderNo(item.getOrderNo());
                trialItems.add(dknTrialItem);
            }
            dknTrialItemService.saveBatch(trialItems);
            dto.setThreadId(dknTrialLog.getId());
            respond.setThreadId(dknTrialLog.getId());

            dto.setApproveNo(orderNum);
            respond.setApproveNo(orderNum);
            Thread thread = new Thread(()->{
                try{
                    ywApproveService.approveCreateBefore(dto);
                }catch (Exception e) {
                    log.error(dto.getUserName()+"业务提审异常:"+e.getMessage(), e);
                    DknTrialLog trialLog=new DknTrialLog();
                    trialLog.setId(dknTrialLog.getId());
                    trialLog.setErrMsg(e.getMessage());
                    dknTrialLogService.updateById(trialLog);
                }

            });
            thread.start();
            return CommonResult.success(respond);
        } catch (Exception e) {
            log.error("流程试算"+e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "定时获取响应结果")
    @PostMapping("/getTimingMap")
    public CommonResult getTimingMap(String threadId) {
        try {
            ApproveRespond timingMap = ywApproveService.getTimingMap(threadId);
            return CommonResult.success(timingMap);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @Schema( name =  "提起审批")
    @PostMapping("/approveSubmit")
    public CommonResult approveSubmit(@RequestParam String id) {
        try {
            DknTrialLog trialLog = dknTrialLogService.getById(id);
            if(UtilValidate.isEmpty(trialLog)){
                return CommonResult.error("参数有误!");
            }
            if(trialLog.getStatus()==0){
                return CommonResult.error("该数据未处理完成!");
            }
            // XftApproveCreateDto
            String body = trialLog.getParameter();
            XftApproveCreateDto submitDto= JSONObject.parseObject(body, XftApproveCreateDto.class);
            List<YwMoneyAffirmLog> list = submitDto.getList();
            for(YwMoneyAffirmLog alog : list){
                YwMoneyAffirmLog byOrderNo = ywMoneyAffirmLogService.getByOrderNo(alog.getOrderNo());
                if(UtilValidate.isNotEmpty(byOrderNo)){
                    return CommonResult.error(alog.getOrderNo()+"该单号不能再提起审批!");
                }

            }
            ywApproveService.approveSubmit(submitDto);
            trialLog.setIsSubmit(1);
            dknTrialLogService.saveOrUpdate(trialLog);
            return CommonResult.success();
        } catch (Exception e) {
            log.error("提起审批"+e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "撤回审批；未审批")
    @PostMapping("/approveCancel")
    public CommonResult approveCancel(String approveId) {
        try {
            ywApproveService.approveCancel(approveId);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "审批作废")
    @PostMapping("/approveAbolish")
    public CommonResult approveAbolish(String approveId) {
        try {
            ywApproveService.approveAbolish(approveId);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "查看审批历史")
    @PostMapping("/approvalHistory")
    public CommonResult approvalHistory(String approveId) {
        try {
            YwApprove approve = ywApproveService.getById(approveId);
            if(UtilValidate.isEmpty(approve)){
                return CommonResult.error("参数有误");
            }
            JSONArray objects = xftService.approvalHistory(approve.getBusKey());
            return CommonResult.success(objects);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }



    @Schema( name =  "业务部门主要抽成比例列表")
    @PostMapping("/deptMainRateList")
    public CommonResult deptMainRateList(@Valid YwDeptMainRateQueryCriteria criteria, YmPageDto ymPage) {
        try {
            TableList<YwDeptMainRate> list = ywDeptMainRateService.list(criteria, ymPage);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "业务部门主要抽成比例保存")
    @PostMapping("/deptMainRateSave")
    public CommonResult deptMainRateSave(YwDeptMainRate rate) {
        try {

            ywDeptMainRateService.saveOrUpdate(rate);
            ywMoneyAffirmLogService.initFn();

            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "业务部门主要抽成比例删除")
    @PostMapping("/deptMainRateDelete")
    public CommonResult deptMainRateDelete(
            @Parameter(name = "数据主键") @RequestParam(required = true) String biaoId) {
        try {
            ywDeptMainRateService.removeById(biaoId);
            ywMoneyAffirmLogService.initFn();
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }



    @Schema( name =  "时俱佳其他客户抽成比例列表")
    @PostMapping("/deptNextRateList")
    public CommonResult deptNextRateList(@Valid YwDeptNextRateQueryCriteria criteria, YmPageDto ymPage) {
        try {
            TableList<YwDeptNextRate> list = ywDeptNextRateService.list(criteria, ymPage);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "时俱佳其他客户抽成比例保存")
    @PostMapping("/deptNextRateSave")
    public CommonResult deptNextRateSave(YwDeptNextRate rate) {
        try {
            ywDeptNextRateService.saveOrUpdate(rate);
            ywMoneyAffirmLogService.initFn();
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "时俱佳其他客户抽成比例删除")
    @PostMapping("/deptNextRateDelete")
    public CommonResult deptNextRateDelete(
            @Parameter(name = "数据主键") @RequestParam(required = true) String shiId) {
        try {
            ywDeptNextRateService.removeById(shiId);
            ywMoneyAffirmLogService.initFn();
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @Schema( name =  "客户列表")
    @RequestMapping(value = "/sellClientSelectList", method = RequestMethod.POST)
    public CommonResult sellClientSelectList(@Valid VSellClientQueryCriteria criteria, YmPageDto pageDto) {
        try {
            TableList<VSellClient> list = vSellClientService.list(criteria, pageDto);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "迪卡侬业务待抽成列表")
    @RequestMapping(value = "/dklMoneyAffirmPageList", method = RequestMethod.POST)
    public CommonResult dklMoneyAffirmPageList(@Valid YwMoneyAffirmLogQueryCriteria criteria, YmPageDto ymPage) {
        try {
            String userName = getUserName();
            String userRole = getUserRole();
            if (!"manage".equals(userRole)) {
                criteria.setUserNameLogin(userName);
            }
            TableList<MsMoneyAffirmOrderDto> list = ywMoneyAffirmLogService.dklMoneyAffirmPageList(criteria, ymPage);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @Schema( name =  "收款确认明细项")
    @PostMapping( "/shouKuanQueRenItemList")
    public CommonResult shouKuanQueRenItemList(FaPiaoItemQueryCriteria criteria) {
        try {

            List<FaPiaoItem> list = ywMoneyAffirmLogService.shouKuanQueRenItemList(criteria);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "收款确认详情 所有 未排除选项")
    @PostMapping( "/shouKuanQueRenItemAllList")
    public CommonResult shouKuanQueRenItemAllList(FaPiaoItemQueryCriteria2 criteria) {
        try {

            List<FaPiaoItem> list = ywMoneyAffirmLogService.shouKuanQueRenItemAllList(criteria);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "已排除 收款确认明细项")
    @PostMapping( "/excludeShouKuanQueRenList")
    public CommonResult excludeShouKuanQueRenList(FaPiaoItemQueryCriteria criteria) {
        try {

            List<ExcludeFaPiaoItem> list = ywMoneyAffirmLogService.excludeShouKuanQueRenList(criteria);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "预收款详情")
    @PostMapping( "/yuShouDetail")
    public CommonResult yuShouDetail(@RequestParam String yushouNo) {
        try {
            VYXXiaoShouYuShouKuanHQueryCriteria criteria=new VYXXiaoShouYuShouKuanHQueryCriteria();
            criteria.setZhuTid(yushouNo);
            List<VYXXiaoShouYuShouKuanH> vyxXiaoShouYuShouKuanHS = vyxXiaoShouYuShouKuanHService.queryAll(criteria);
            VYXXiaoShouYuShouKuanH detail=null;
            if(UtilValidate.isNotEmpty(vyxXiaoShouYuShouKuanHS)){
                detail=vyxXiaoShouYuShouKuanHS.get(0);
                if(UtilValidate.isNotEmpty(detail.getShouKuanRiQi())){
                    Date date=new Date(detail.getShouKuanRiQi().getTime());
                    String s = DateKit.dateFormat(date,"yyyy-MM-dd");
                    detail.setShouKuanRiQiValue(s);
                }
//                FaPiaoItemQueryCriteria c2=new FaPiaoItemQueryCriteria();
//                c2.setSkqrNo(yushouNo);
//                List<FaPiaoItem> faPiaoItems = ywMoneyAffirmLogService.yushoukuanItemList(c2);
//                detail.setItems(faPiaoItems);
            }
            return CommonResult.success(detail, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @Schema( name =  "期初数据 列表")
    @PostMapping( "/qiChuItemList")
    public CommonResult qiChuItemList(QiChuQueryCriteria criteria) {
        try {

            List<QiChuItem> list = ywMoneyAffirmLogService.qiChuItemList(criteria);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @Schema( name =  "期初数据 一条")
    @PostMapping( "/qiChuItemOne")
    public CommonResult qiChuItemOne(QiChuQueryCriteria criteria) {
        try {

            QiChuItem list = ywMoneyAffirmLogService.qiChuItemOne(criteria);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "增加 排除 抽成")
    @PostMapping("/addExcludeAffirmLog")
    public CommonResult addExcludeAffirmLog(@RequestBody YwApproveCreateDto dto) {
        try {
            String userId = getUserId();

            String userRole = getUserRole();
            if (!"manage".equals(userRole)) {

            }
           ywMoneyAffirmLogService.addExcludeAffirmLog(dto);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }





    @Schema( name =  "获取 排除 抽成")
    @PostMapping("/getExcludeAffirmList")
    public CommonResult getExcludeAffirmList(@RequestParam String types) {
        try {
            List<YwMoneyAffirmLog> affirmList = ywMoneyAffirmLogService.getExcludeAffirmList(types);
            return CommonResult.success(affirmList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @Schema( name =  "删除 排除 抽成")
    @PostMapping("/removeExcludeAffirmLog")
    public CommonResult removeExcludeAffirmLog(String id) {
        try {
            ywMoneyAffirmLogService.removeExcludeAffirmLog(id);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "获取暂存列表")
    @PostMapping("/getOrderNoStorageList")
    public CommonResult orderNoStorageList(@RequestParam String type) {
        try {
            String userId = getUserId();
            List<MsMoneyAffirmDto> list = ywMoneyOrderNoStorageService.getByUserId(userId,type);
            return CommonResult.success(list);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @Schema( name =  "保存暂存")
    @PostMapping("/saveOrderNoStorage")
    public CommonResult saveOrderNoStorage(@RequestParam String orderNo, @RequestParam String type) {
        try {
            if(UtilValidate.isEmpty(orderNo)){
                return CommonResult.error("无可暂存数据！");
            }
            String[] split = orderNo.split(",");
            String userId = getUserId();
            String userName = getUserName();
            List<YwMoneyOrderNoStorage> list = new ArrayList<>();
            for (String s : split) {
                YwMoneyOrderNoStorage byId = ywMoneyOrderNoStorageService.getById(s);
                if(UtilValidate.isEmpty(byId)){
                   // return CommonResult.error(s+"该单号已经暂存过了，请刷新列表后在查看!");
                    YwMoneyOrderNoStorage storage = new YwMoneyOrderNoStorage();
                    storage.setOrderNo(s);
                    storage.setUserId(userId);
                    storage.setUserName(userName);
                    storage.setType(type);
                    list.add(storage);
                }else{
                    return CommonResult.error(s+"该单号已经暂存过了，请刷新列表后在查看!");
                }

            }
            if(UtilValidate.isNotEmpty(list)){
                ywMoneyOrderNoStorageService.saveOrUpdateBatch(list);
            }
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @Schema( name =  "删除暂存")
    @PostMapping("/removeOrderNoStorage")
    public CommonResult removeOrderNoStorage(@RequestParam String orderNo) {
        try {
            if(UtilValidate.isEmpty(orderNo)){
                return CommonResult.error("非法参数");
            }
            ywMoneyOrderNoStorageService.removeById(orderNo);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "获取部门金额统计")
    @PostMapping("/getCountDeptTotalLog")
    public CommonResult getCountDeptTotalLog(String month) {
        try {

            CountMoneyAffirmDto countDeptTotalLog = ywMoneyAffirmLogService.getCountDeptTotalLog( month);
            Map<String,Object> map = new HashMap<>();
            map.put("totalData",countDeptTotalLog);

            return CommonResult.success(map);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }



    @Schema( name =  "介绍人列表")
    @PostMapping("/introduceUserList")
    public CommonResult introduceUserList(@Valid YwIntroduceUserQueryCriteria criteria, YmPageDto ymPage) {
        try {
            TableList<YwIntroduceUser> list = ywIntroduceUserService.list(criteria, ymPage);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "介绍人保存")
    @PostMapping("/introduceUserSave")
    public CommonResult introduceUserSave(YwIntroduceUser user) {
        try {

            ywIntroduceUserService.saveOrUpdate(user);

            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "介绍人删除")
    @PostMapping("/introduceUserDelete")
    public CommonResult introduceUserDelete(
            @Parameter(name = "数据主键") @RequestParam(required = true) String id) {
        try {
            ywIntroduceUserService.removeById(id);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @Schema( name =  "查询提审等待队列")
    @RequestMapping(value = "/trialLogList", method = RequestMethod.POST)
    public CommonResult trialLogList(@RequestParam Integer type) {
        try {
            String userName = getUserName();
            String userRole = getUserRole();
            if ("manage".equals(userRole)) {
                userName ="刘庆峰";
            }
            DbUser dbUser = dbUserService.findByUserName(userName);
            String userId = getUserId();
            if(UtilValidate.isNotEmpty(dbUser)){
                userId = dbUser.getUserId();
            }
            DknTrialLogQueryCriteria criteria=new DknTrialLogQueryCriteria();
            criteria.setUserId(userId);
            criteria.setType(type);
            criteria.setIsRead(0);
//            criteria.setStatus(0);
//            criteria.setIsSubmit(0);
            List<DknTrialLog> list = dknTrialLogService.queryAll(criteria);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @Schema( name =  "查询提审等待队列")
    @RequestMapping(value = "/trialLogRead", method = RequestMethod.POST)
    public CommonResult trialLogRead(@RequestParam String id) {
        try {
            DknTrialLog trialLog = dknTrialLogService.getById(id);
            if(UtilValidate.isNotEmpty(trialLog)){
                //return CommonResult.error("参数有误!");
                if(trialLog.getIsSubmit()==1){
                    DknTrialLog n=new DknTrialLog();
                    n.setId(id);
                    n.setIsRead(1);
                    dknTrialLogService.updateById(n);
                }

            }

            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "查看排除项")
    @RequestMapping(value = "/getExcludeFapiaoList", method = RequestMethod.POST)
    public CommonResult getExcludeFapiaoList(FaPiaoItemQueryCriteria criteria) {
        try {
            String userId = getUserId();
//            criteria.setExclude_userId(userId);
            List<ExcludeFaPiaoItem> items = ywMoneyAffirmLogService.excludeShouKuanQueRenList(criteria);
            return CommonResult.success(items);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "批量添加排除项")
    @RequestMapping(value = "/batchExcludeFapiaoAdd", method = RequestMethod.POST)
    public CommonResult batchExcludeFapiaoAdd(@RequestBody BatchExcludeFapiaoDto dto) {
        try {
            ywExcludeFapiaoItemService.batchExcludeFapiaoAdd(dto);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "批量移除排除项")
    @RequestMapping(value = "/batchExcludeFapiaoRemove", method = RequestMethod.POST)
    public CommonResult batchExcludeFapiaoRemove(@RequestBody BatchExcludeFapiaoDto dto) {
        try {
            ywExcludeFapiaoItemService.batchExcludeFapiaoRemove(dto);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

    @Schema( name =  "删除排除项")
    @RequestMapping(value = "/oneExcludeFapiaoRemove", method = RequestMethod.POST)
    public CommonResult oneExcludeFapiaoRemove(String id) {
        try {
            ywExcludeFapiaoItemService.removeById(id);
            return CommonResult.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }


    @Schema( name =  "查看已抽成记录")
    @RequestMapping(value = "/tablePassAffirmList", method = RequestMethod.POST)
    public CommonResult tablePassAffirmList(@Valid YwMoneyAffirmLogQueryCriteria criteria, YmPageDto ymPage) {
        try {
            TableList<YwMoneyAffirmLog> list = ywMoneyAffirmLogService.tablePassAffirmList(criteria, ymPage);
            return CommonResult.success(list, "获取成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResult.error(e.getMessage());
        }
    }

}
